package com.atguigu.vod.vodService.vodServiceImpl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.utils.ConstantProperties;
import com.atguigu.vod.utils.InitVodClient;
import com.atguigu.vod.vodService.VodService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author ty
 */
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadAliyunVideo(MultipartFile file) {
        try {
            String accessKeyId = ConstantProperties.ACCESSKEYID;
            String accessKeySecret = ConstantProperties.ACCESSKEYSECRET;
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            int index = fileName.lastIndexOf(".");
            String title = fileName.substring(0,index);
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：" + "code：" +
                        response.getCode() + ", message：" + response.getMessage();
                System.out.println(errorMessage);
            } else {
                videoId =response.getVideoId();
            }
            return videoId;
        } catch (IOException e) {
            throw new GuliException(20001, "guli vod 服务上传失败");
        }
    }

    @Override
    public void removeMoreAlyVideo(List videoIdList) {
        try {
            DefaultAcsClient client = InitVodClient.initClient(ConstantProperties.ACCESSKEYID,ConstantProperties.ACCESSKEYSECRET);
            DeleteVideoRequest deleteVideoRequest = new DeleteVideoRequest();
            String videoIds = StringUtils.join(videoIdList.toArray(), ",");
            deleteVideoRequest.setVideoIds(videoIds);
            client.getAcsResponse(deleteVideoRequest);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除失败");
        }
    }
}
